package com.hmdp.utils;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

@Component
public class RedisIdWorker {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    private static final long BEGIN=1640995200;

    private static final long PERIOD_BITS=32;

    public long nextId(String prefix){
        //1. 构建时间部
        LocalDateTime now = LocalDateTime.now();
        long offset = now.toEpochSecond(ZoneOffset.UTC) - BEGIN;

        //2. 构建递增部
        String nowStr = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        long increment = stringRedisTemplate.opsForValue().increment("icr:" + prefix + ":" + nowStr);

        //3. 拼接

        return offset<<PERIOD_BITS|increment;
    }

//    public static void main(String[] args) {
//        LocalDateTime begin = LocalDateTime.of(2022, 1, 1, 0, 0, 0);
//        System.out.println("begin.toEpochSecond(ZoneOffset.UTC) = " + begin.toEpochSecond(ZoneOffset.UTC));
//    }
}
